package com.acc.store.service.impl;

import com.acc.store.entity.Inventory;
import com.acc.store.entity.Supplier;
import com.acc.store.mapper.InventoryMapper;
import com.acc.store.service.InventoryService;
import com.acc.store.vo.InventoryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 10067
 * @description 针对表【inventory(仓储表)】的数据库操作Service实现
 * @createDate 2023-10-13 18:05:02
 */
@Service
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, Inventory>
        implements InventoryService {
    @Override
    public IPage getPage(Map<String, Object> params) {
        Long page = Long.valueOf((String) params.get("page"));
        Long limit = Long.valueOf((String) params.get("limit"));
        String key = (String) params.get("key");
        //封装查询语句
        Page<Inventory> page1 = lambdaQuery().like(!StringUtils.isNullOrEmpty(key)
                , Inventory::getProductId, key).page(new Page<>(page, limit));
        Page<InventoryVo> voPage = new Page<>();
        BeanUtils.copyProperties(page1, voPage, "records");
        List<InventoryVo> vos = page1.getRecords().stream().map(inventory -> {
            Supplier byId = Db.getById(inventory.getSupplierId(), Supplier.class);
            InventoryVo inventoryVo = new InventoryVo();
            BeanUtils.copyProperties(inventory, inventoryVo);
            inventoryVo.setSupplierName(byId.getName());
            return inventoryVo;
        }).toList();
        voPage.setRecords(vos);
        return voPage;
    }

    @Override
    public void saveOne(Inventory inventory) {
        inventory.setQuantityListed(0);
        inventory.setStockInTime(new Date());
        save(inventory);
    }

    @Override
    public void grouding(Long id, Integer num) {
        Inventory byId = getById(id);
        byId.setQuantityListed(byId.getQuantityListed() + num);
        Integer temp=byId.getQuantityInStock() - num;
        if (temp<0){
            throw new RuntimeException("无中生有，笨蛋");
        }
        byId.setQuantityInStock(temp);
        updateById(byId);
    }

}




